//
//  RegisterController.m
//  projectBase
//
//  Created by zhuangzhh on 15/5/11.
//  Copyright (c) 2015年 zhuangzhh. All rights reserved.
//

#import "RegisterController.h"
#import "JKCountDownButton.h"
#import "DSToast.h"

#define LineWidth  .5
#define RowHigh    38
#define SmsBtnTag  20001

@interface RegisterController ()
{
    JKCountDownButton *_countDownCode;
}

@end

@implementation RegisterController
//-(void)register:(NSString *)mobile pwd:(NSString *)pwd nickName:(NSString *)nickName code:(NSString *)code recommendcode:(NSString *)recommend
-(void)register:(NSString *)mobile pwd:(NSString *)pwd code:(NSString *)code
{
    [self showLoadViewExt:CGRectMake(0, 0, ScreenWidth, ScreenHeight-TopAndSystemHeight) backColor:[UIColor clearColor] info:@"正在加载中，请稍候..."];
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:mobile,@"username",code,@"code",pwd,@"password",nil];
    [[HttpBaseModel getInstance] getDataResponsePath:[NSString stringWithFormat:@"user/register"] params:param httpMethod:@"POST" onCompletion:^(NSData *responseData){
        
        [self closeLoadView];
        NSError *error = nil;
        id resultString = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
        if (error)
        {
            NSLog(@"dic->%@",error);
        }
        else
        {
            ResponseCell *response = [[ResponseCell alloc] initWithDictionary:resultString error:NULL];
            if(response.success == 1)
            {
//                DSToast *toast = [[DSToast alloc]initWithText:response.msg];
//                [toast showInView:self.view];
//                [self showTipInfo:response.msg];
//                [[ViewManager shareInstance].NavigationController popViewControllerAnimated:YES];
                
                UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"恭喜您" message:@"注册成功！" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *ac=[UIAlertAction actionWithTitle:@"我知道啦" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [[ViewManager shareInstance].NavigationController popViewControllerAnimated:YES];
                    
                }];
                [alert addAction:ac];
                [self presentViewController:alert animated:YES completion:nil];
                
                
            }
            else
            {
                DSToast *toast = [[DSToast alloc]initWithText:response.msg];
                [toast showInView:self.view];
//                [self showTipInfo:response.msg];
            }
            
        }
        
        
        
    } onError:^(NSError *error){
        DSToast *toast = [[DSToast alloc]initWithText:@"网络异常，请重试！"];
        [toast showInView:self.view];
//        [self showTipInfo:@"网络异常，请重试！"];
        [self closeLoadView];
    }];

}

-(void)initUI
{
    [super initUI];
    
    [self setTopTitle:_barTitle];
    [self setTopTitleColor:[UIColor whiteColor]];
    
    self.view.backgroundColor = MainBgColor;

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, TopBarHeight+15, ScreenWidth, LineWidth)];
    line.backgroundColor = [UIColor lightGrayColor];
    line.alpha = .5;
    [self.view addSubview:line];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, LineWidth+line.frame.origin.y, ScreenWidth, RowHigh)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    
    _phoneText = [[UITextField alloc] initWithFrame:CGRectMake(13, LineWidth+line.frame.origin.y, ScreenWidth-26, RowHigh)];
    UIColor *color = UIColorRGB(170);
    _phoneText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号，用于接收验证码" attributes:@{NSForegroundColorAttributeName: color}];
    _phoneText.backgroundColor = [UIColor whiteColor];
    _phoneText.keyboardType = UIKeyboardTypeNumberPad;
    _phoneText.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:_phoneText];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, _phoneText.frame.size.height+_phoneText.frame.origin.y, ScreenWidth, LineWidth)];
    line1.backgroundColor = [UIColor lightGrayColor];
    line1.alpha = .5;
    [self.view addSubview:line1];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, line1.frame.size.height+line1.frame.origin.y+15, ScreenWidth, LineWidth)];
    line2.backgroundColor = [UIColor lightGrayColor];
    line2.alpha = .5;
    [self.view addSubview:line2];
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, LineWidth+line2.frame.origin.y, ScreenWidth, RowHigh)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    
    _smsText = [[UITextField alloc] initWithFrame:CGRectMake(13, LineWidth+line2.frame.origin.y, ScreenWidth-26, RowHigh)];
    _smsText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"验证码" attributes:@{NSForegroundColorAttributeName: color}];
//    _smsText.placeholder = @"验证码";
    _smsText.keyboardType = UIKeyboardTypeNumberPad;
    _smsText.backgroundColor= [UIColor whiteColor];
    _smsText.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:_smsText];
    
//    UIButton *smsBtn = [self createBtn:CGRectMake(ScreenWidth-70, _smsText.frame.origin.y+8, 60, RowHigh-16) title:@"获取验证码" iconImage:nil backgroundImage:nil tag:SmsBtnTag textColor:[UIColor whiteColor]];
//    smsBtn.backgroundColor = MainColor;
//    smsBtn.layer.cornerRadius = 3.0;
//    smsBtn.layer.masksToBounds = YES;
//    smsBtn.titleLabel.font = [UIFont systemFontOfSize:10];
//    [self.view addSubview:smsBtn];
    
    _countDownCode = [JKCountDownButton buttonWithType:UIButtonTypeCustom];
    _countDownCode.frame = CGRectMake(ScreenWidth-70, _smsText.frame.origin.y+8, 60, RowHigh-16);
    [_countDownCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    _countDownCode.backgroundColor = MainColor;
    _countDownCode.layer.cornerRadius = 3.0;
    _countDownCode.layer.masksToBounds = YES;
    _countDownCode.titleLabel.font = [UIFont systemFontOfSize:10];
    [self.view addSubview:_countDownCode];
    
    
    [_countDownCode addToucheHandler:^(JKCountDownButton*sender, NSInteger tag) {
        
        [_phoneText resignFirstResponder];
        if([PubFunction stringIsNullOrEmpty:_phoneText.text] || _phoneText == nil)
        {
            DSToast *toast = [[DSToast alloc]initWithText:@"手机号不能为空！"];
            return;
        }
        
        if(![self isMobileNumber:_phoneText.text])
        {
            DSToast *toast = [[DSToast alloc]initWithText:@"请输入合法手机号！"];
            [toast showInView:self.view];
            return;
        }

        [self getValidateCode:_phoneText.text];
        
        sender.enabled = NO;
        
        [sender startWithSecond:60];
        
        [sender didChange:^NSString *(JKCountDownButton *countDownButton,int second) {
            NSString *title = [NSString stringWithFormat:@"剩余%d秒",second];
            return title;
        }];
        [sender didFinished:^NSString *(JKCountDownButton *countDownButton, int second) {
            countDownButton.enabled = YES;
            return @"重新获取";
            
        }];
        
    }];
    
    
    
    UIView *line3 = [[UIView alloc] initWithFrame:CGRectMake(0, _smsText.frame.size.height+_smsText.frame.origin.y, ScreenWidth, LineWidth)];
    line3.backgroundColor = [UIColor lightGrayColor];
    line3.alpha = .5;
    [self.view addSubview:line3];
    
    UIView *line4 = [[UIView alloc] initWithFrame:CGRectMake(0, line3.frame.size.height+line3.frame.origin.y+15, ScreenWidth, LineWidth)];
    line4.hidden = YES;
    line4.backgroundColor = [UIColor lightGrayColor];
    line4.alpha = .6;
    [self.view addSubview:line4];
    
//    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, LineWidth+line4.frame.origin.y, ScreenWidth, RowHigh)];
//    view2.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:view2];
//    
//    _nicknameText = [[UITextField alloc] initWithFrame:CGRectMake(13, LineWidth+line4.frame.origin.y, ScreenWidth-26, RowHigh)];
//    _nicknameText.placeholder = @"请输入昵称";
//    _nicknameText.backgroundColor = [UIColor whiteColor];
//    _nicknameText.font = [UIFont systemFontOfSize:14];
//    [self.view addSubview:_nicknameText];
//    
//    UIView *line5 = [[UIView alloc] initWithFrame:CGRectMake(0, _nicknameText.frame.size.height+_nicknameText.frame.origin.y, ScreenWidth, LineWidth)];
//    line5.backgroundColor = [UIColor lightGrayColor];
//    line5.alpha = .6;
//    [self.view addSubview:line5];
    
    UIView *line6 = [[UIView alloc] initWithFrame:CGRectMake(0, line4.frame.size.height+line4.frame.origin.y+15, ScreenWidth, LineWidth)];
    line6.backgroundColor = [UIColor lightGrayColor];
    line6.alpha = .6;
    [self.view addSubview:line6];
//
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(0, LineWidth+line6.frame.origin.y, ScreenWidth, RowHigh)];
    view3.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view3];
    
    _pwdText = [[UITextField alloc] initWithFrame:CGRectMake(13, LineWidth+line6.frame.origin.y, ScreenWidth-26, RowHigh)];
    _pwdText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName: color}];
//    _pwdText.placeholder = @"请输入密码";
    _pwdText.secureTextEntry = YES;
    _pwdText.backgroundColor = [UIColor whiteColor];
    _pwdText.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:_pwdText];
    
    UIView *line7 = [[UIView alloc] initWithFrame:CGRectMake(0, _pwdText.frame.size.height+_pwdText.frame.origin.y, ScreenWidth, LineWidth)];
    line7.backgroundColor = [UIColor lightGrayColor];
    line7.alpha = .6;
    [self.view addSubview:line7];
    
    
//    UIView *line8 = [[UIView alloc] initWithFrame:CGRectMake(0, line7.frame.size.height+line7.frame.origin.y+15, ScreenWidth, LineWidth)];
//    line8.backgroundColor = [UIColor lightGrayColor];
//    line8.alpha = .6;
//    [self.view addSubview:line8];
    //
//    UIView *view4 = [[UIView alloc] initWithFrame:CGRectMake(0, LineWidth+line8.frame.origin.y, ScreenWidth, RowHigh)];
//    view4.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:view4];
//    
//    _codeText = [[UITextField alloc] initWithFrame:CGRectMake(13, LineWidth+line8.frame.origin.y, ScreenWidth-26, RowHigh)];
//    _codeText.placeholder = @"请输入推荐人手机号";
//    _codeText.secureTextEntry = YES;
//    _codeText.backgroundColor = [UIColor whiteColor];
//    _codeText.font = [UIFont systemFontOfSize:14];
//    [self.view addSubview:_codeText];
//    
//    UIView *line9 = [[UIView alloc] initWithFrame:CGRectMake(0, _codeText.frame.size.height+_codeText.frame.origin.y, ScreenWidth, LineWidth)];
//    line9.backgroundColor = [UIColor lightGrayColor];
//    line9.alpha = .6;
//    [self.view addSubview:line9];
    
    UIButton *registerBtn = [self createBtn:CGRectMake(13, line7.frame.size.height+line7.frame.origin.y+25, ScreenWidth-26, 34) title:@"提交" iconImage:nil backgroundImage:nil tag:0 textColor:[UIColor whiteColor]];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    registerBtn.layer.cornerRadius = 3.0;
    registerBtn.backgroundColor = MainColor;
    [self.view addSubview:registerBtn];
    
    

}



-(void)btnAction:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    int tag = [btn tag];
    if(tag == SmsBtnTag)
    {
        if([PubFunction stringIsNullOrEmpty:_phoneText.text] || _phoneText == nil)
        {
            DSToast *toast = [[DSToast alloc]initWithText:@"手机号不能为空！"];
            [toast showInView:self.view];
            return;
        }
        if(![self isMobileNumber:_phoneText.text])
        {
            DSToast *toast = [[DSToast alloc]initWithText:@"请输入合法手机号！"];
            [toast showInView:self.view];
            return;
        }
        [self getValidateCode:_phoneText.text];
    }
    else
    {
        [self closekeyBoard];
        if([PubFunction stringIsNullOrEmpty:_phoneText.text] || _phoneText == nil)
        {
            DSToast *toast = [[DSToast alloc]initWithText:@"手机号不能为空！"];
            [toast showInView:self.view];
            return;
        }
        if([PubFunction stringIsNullOrEmpty:_smsText.text] || _smsText.text == nil)
        {
            DSToast *toast = [[DSToast alloc]initWithText:@"验证码不能为空！"];
            [toast showInView:self.view];
           
            return;
        }
//        if([PubFunction stringIsNullOrEmpty:_nicknameText.text] || _nicknameText.text == nil)
//        {
//            DSToast *toast = [[DSToast alloc]initWithText:@"昵称不能为空！"];
//            [toast showInView:self.view];
//            return;
//        }
        if([PubFunction stringIsNullOrEmpty:_pwdText.text] || _pwdText.text == nil)
        {
            DSToast *toast = [[DSToast alloc]initWithText:@"密码不能为空！"];
            [toast showInView:self.view];
            return;
        }
        
//        NSString *code = [AppData getpersonshopmid];
//        if([PubFunction stringIsNullOrEmpty:_codeText.text] || _codeText.text == nil)
//        {
//            code = @"";
//        }
//        else
//        {
//            code = _codeText.text;
//        }

//        [self register:_phoneText.text pwd:_pwdText.text nickName:_nicknameText.text code:_smsText.text recommendcode:code];
        
        
        [self register:_phoneText.text pwd:_pwdText.text code:_smsText.text];
        
        
    }

}

-(void)closekeyBoard
{
    [_phoneText resignFirstResponder];
    [_nicknameText resignFirstResponder];
    [_smsText resignFirstResponder];
    [_pwdText resignFirstResponder];

}


-(void)getValidateCode:(NSString *)mobile
{
    if(mobile == nil&&![PubFunction stringIsNullOrEmpty:mobile])
        return;
    [self showLoadViewExt:CGRectMake(0, 0, ScreenWidth, ScreenHeight-TopAndSystemHeight) backColor:[UIColor clearColor] info:@"正在加载中，请稍候..."];
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:mobile,@"username",nil];
    [[HttpBaseModel getInstance] getDataResponsePath:[NSString stringWithFormat:@"user/regSendSms"] params:param httpMethod:@"POST" onCompletion:^(NSData *responseData){
        
        [self closeLoadView];
        NSError *error = nil;
        id resultString = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
        if (error)
        {
            NSLog(@"dic->%@",error);
        }
        else
        {
            ResponseCell *response = [[ResponseCell alloc] initWithDictionary:resultString error:NULL];
            if(response.success == 1)
            {
                DSToast *toast = [[DSToast alloc]initWithText:@"短信发送，请查收！"];
                [toast showInView:self.view];
            }
            else
            {
                [_countDownCode stop];
                DSToast *toast = [[DSToast alloc]initWithText:response.msg];
                [toast showInView:self.view];
//                [self showTipInfo:response.msg];
            }
            
        }
    } onError:^(NSError *error){
        [self showTipInfo:@"网络异常，请重试！"];
        [self closeLoadView];
    }];
    
}

- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((77|33|53|8[09])[0-9]|349)\\d{7}$";
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

@end
